package com.zbkj.crmeb.open;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.crmeb.core.common.CommonResult;
import com.utils.DateUtil;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.request.StoreProductRequest;
import com.zbkj.crmeb.store.request.StoreProductStockRequest;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.StoreCartService;
import com.zbkj.crmeb.store.service.StoreProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 商品表 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("api/open/store")
@Api(tags = "商品") //配合swagger使用
public class OpenStoreApiController {

    @Autowired
    private StoreProductService storeProductService;

    @Autowired
    private StoreCartService storeCartService;

    @Autowired
    private StoreBrandService storeBrandService;
    /**
     * 新增商品表
     * @param storeProductRequest 新增参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "导入商品")
    @RequestMapping(value = "/product/import", method = RequestMethod.POST)
    public CommonResult<String> saveProduct(@RequestBody @Validated StoreProductRequest storeProductRequest) throws Exception {
        boolean newProduct = true;
        boolean resultFlag = false;
        //最后推送时间
        storeProductRequest.setLastPushTime(DateUtil.nowDateTime());
        if(storeProductRequest.getId()!=null){
            newProduct = false;
            // update
        }else if(StringUtils.isNotBlank(storeProductRequest.getBarCode())){
            StoreProduct sp = storeProductService.getByBarCode(storeProductRequest.getBarCode());
            if(sp!=null){
                storeProductRequest.setId(sp.getId());
                newProduct = false;
            }
        }

        if(newProduct){
            resultFlag = storeProductService.save(storeProductRequest);
        }else{
            resultFlag = storeProductService.update(storeProductRequest);
        }

       if (resultFlag) {
            log.warn("买手端消费数据 - 添加或更新商品 - 成功, barCode:{} and price:{} and stock:{} and sourceCost:{} ", storeProductRequest.getBarCode(), storeProductRequest.getPrice(), storeProductRequest.getStock(), storeProductRequest.getSourceCost());
            return CommonResult.success();
        }

        return CommonResult.failed();
    }

    /**
     * 上架
     * @param id integer id
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "上架")
    @RequestMapping(value = "/product/putOnShell/{id}", method = RequestMethod.GET)
    public CommonResult<String> putOn(@PathVariable Integer id){
        StoreProduct storeProduct = new StoreProduct();
        storeProduct.setId(id);
        storeProduct.setIsShow(true);
        if(storeProductService.updateById(storeProduct)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 下架
     * @param barCode
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "下架")
    @RequestMapping(value = "/product/offline/{barCode}", method = RequestMethod.GET)
    public CommonResult<String> offShell(@PathVariable String barCode) throws Exception {

        StoreProduct storeProduct = storeProductService.getByBarCode(barCode);
        if(storeProduct==null){
            log.warn("买手端消费数据 - 下架商品 - not exists! barCode: {}",barCode);
            return CommonResult.failed();
        }
        storeProduct.setIsShow(false);
        if(storeProductService.updateById(storeProduct)){
            storeCartService.productStatusNotEnable(storeProduct.getId());
            log.warn("买手端消费数据 - 下架商品 - 成功, barCode:{} ", barCode);
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 库存变动
     * @param request StoreProductStockRequest 参数
     * @author Mr.Zhang
     * @since 2020-05-19
     */
    @ApiOperation(value = "库存变动")
    @RequestMapping(value = "/product/stock", method = RequestMethod.GET)
    public CommonResult<String> stock(@Validated StoreProductStockRequest request){
        if(storeProductService.stockAddRedis(request)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 新增商品表
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "导入商品")
    @RequestMapping(value = "/brand/import", method = RequestMethod.POST)
    public CommonResult<String> importBrandList(@RequestBody @Validated List<StoreBrand> brandList){
        if(CollectionUtils.isNotEmpty(brandList)){
            List<StoreBrand> oldBrandList = storeBrandService.list();
            Map<Integer,StoreBrand> oldMap = oldBrandList.stream().collect(Collectors.toMap(StoreBrand::getId, Function.identity(),(old, newData)->newData));
            brandList.forEach(brand->{
                if(oldMap.containsKey(brand.getId())){
                    brand.setId(oldMap.get(brand.getId()).getId());
                    storeBrandService.updateById(brand);
                }else{
                    storeBrandService.save(brand);
                }
            });

        }
        return CommonResult.failed();
    }
}



